//
//  WelcomeViewController.swift
//  sinaOnceAgain
//
//  Created by 王相超 on 16/2/19.
//  Copyright © 2016年 chuanzhi. All rights reserved.
//

import UIKit
import SDWebImage
import SnapKit

class WelcomeViewController: UIViewController {
    
    override func loadView() {
        
        //自定义根视图
        view = UIImageView(image: UIImage(named: "ad_background"))
    }

    override func viewDidLoad() {
        super.viewDidLoad()
     
        setupUI()
       
    }
    
    override func viewDidAppear(animated: Bool) {
        
        super.viewDidAppear(animated)
        startAnimation()
    }
    
    //设置页面信息
    private func setupUI() {
        
        view.addSubview(iconView)
        view.addSubview(welcomeLabel)
        
        //设置子视图的约束
        iconView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(view.snp_centerX)
            make.bottom.equalTo(view.snp_bottom).offset(-160)
            
            //约束头像的大小  是像素的一半
            make.size.equalTo(CGSizeMake(90, 90))
        }
        
        welcomeLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(iconView.snp_centerX)
            make.top.equalTo(iconView.snp_bottom).offset(16)
        }
        
        //最初文案是隐藏的  等到用户头像动画结束时  显示文案
        welcomeLabel.alpha = 0
        
         iconView.sd_setImageWithURL(UserAccountViewModel.sharedAccountViewModel.headImageURL)
        
        //设置用户头像圆角
        iconView.layer.cornerRadius = 45
        //裁剪
        iconView.layer.masksToBounds = true
        
    }
    
    //头像的动画效果
    private func startAnimation() {
        
         let offset = -UIScreen.mainScreen().bounds.height + 160
        
        self.iconView.snp_updateConstraints(closure: { (make) -> Void in
            make.bottom.equalTo(self.view.snp_bottom).offset(offset)
        })
        
      UIView.animateWithDuration(1.2, delay: 0, usingSpringWithDamping: 0.98, initialSpringVelocity: 9.8, options: [], animations: { () -> Void in
        
        //设置强制更新页面
        self.view.layoutIfNeeded()
        
        }) { (_) -> Void in
            
            //显示文案
            UIView.animateWithDuration(0.5, animations: { () -> Void in
                self.welcomeLabel.alpha = 1
                }, completion: { (_) -> Void in
                    
                 //欢迎文案显示之后  切换根视图控制器
                    
                NSNotificationCenter.defaultCenter().postNotificationName(KChoseRootVC, object: "welcomle")
                    
            })
        }
    
    
    }
    //懒加载子视图
    
      //用户头像
    private lazy var iconView: UIImageView = UIImageView(image: UIImage(named: "avatar_default_big"))
    
      //欢迎的文案
    private lazy var welcomeLabel: UILabel = UILabel(text: (UserAccountViewModel.sharedAccountViewModel.userName ?? "") + "欢迎摸摸大", fontSize: 19, textColor: UIColor.darkGrayColor())
}
